<template>
  <el-dialog
    :title="props.serverId ? '编辑服务器' : '新增服务器'"
    v-model="visible"
    width="60%"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <ServerForm
      v-if="visible"
      :initial-data="initialData"
      @submit="handleSubmit"
      @cancel="visible = false"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { ServerInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import ServerForm from './ServerForm.vue'

interface Props {
  modelValue: boolean
  serverId?: number
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const initialData = ref<Partial<ServerInfo>>({})

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val
    if (val && props.serverId) {
      fetchServerData()
    }
  },
)

// 监听 visible 变化
watch(
  () => visible.value,
  (val) => {
    emit('update:modelValue', val)
  },
)

// 获取服务器数据
const fetchServerData = async () => {
  if (!props.serverId) return
  try {
    const data = await assetService.getServerById(props.serverId)
    initialData.value = data
  } catch (err) {
    console.error('获取服务器数据失败:', err)
    ElMessage.error('获取服务器数据失败')
    visible.value = false
  }
}

// 处理表单提交
const handleSubmit = async (data: ServerInfo) => {
  try {
    if (props.serverId) {
      await assetService.updateServer(props.serverId, data)
      ElMessage.success('更新成功')
    } else {
      await assetService.createServer(data)
      ElMessage.success('创建成功')
    }
    visible.value = false
    emit('success')
  } catch (err) {
    console.error('保存服务器失败:', err)
    ElMessage.error('保存失败')
  }
}

// 对话框关闭后清理数据
const handleClosed = () => {
  initialData.value = {}
}
</script>
